package com.scalar.chiptrack.adaptor.umc;

import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;

import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.HTML;
import javax.swing.text.html.parser.DTD;
import javax.swing.text.html.parser.DocumentParser;
import javax.swing.text.MutableAttributeSet;
import java.util.ArrayList;
import java.util.Date;
import java.io.BufferedReader;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 9 Nov, 2009
 * Time: 2:34:50 PM
 */
public class UMCHtmlParser  extends HTMLEditorKit.ParserCallback {      

    private ArrayList m_urlList = new ArrayList();

    private int m_cellIndex;
    private int m_tableIndex;
    private boolean m_cellOpen;
    private boolean m_tableFound = false;
    private boolean m_validUrl = false;
    private String m_urlString = null;
    private static int sortLotBinDaysDiff = 6;

    public UMCHtmlParser() {

        m_cellOpen = false;
        m_cellIndex = -1;
        m_tableIndex = 0;

    }

    //Parser returns the ArrayList of URL's
    public ArrayList parse (BufferedReader reader) throws Exception {

        DTD dtd = DTD.getDTD ("HTML");
        DocumentParser documentParser = new DocumentParser (dtd);
        documentParser.parse (reader, this, true /*ignore CharSet*/);

        return m_urlList;
    }

    public void handleSimpleTag (HTML.Tag t, MutableAttributeSet a, int pos) {


       //Got a new Table
        if(t == HTML.Tag.TABLE){
        	m_tableIndex++;

        	if(m_tableIndex == 3){
        		m_tableFound = true;
        	}else{
        		m_tableFound = false;
        	}
        }

        // Got a new row
        if (t == HTML.Tag.TR) {

			if(m_tableFound){

				m_cellOpen = false;
        		m_cellIndex = -1;
        		m_validUrl = false;
 			}
        }

        // Got a new cell
        if (t == HTML.Tag.TD) {

        	if(m_tableFound){
        		if(m_cellOpen == false){

        			m_cellIndex++;
        			m_cellOpen = true;

        		}else{

        			m_cellOpen = false;

        		}
        	}
        }

        //Got a new A tag
        if(t == HTML.Tag.A){

        	if(m_validUrl){

        		m_urlString = parseLotBinSummaryDownloadLink((String)a.getAttribute(HTML.Attribute.HREF));
        		//System.out.println("Download link = "+m_urlString);
        	}
        }
    }

    public void handleText (char[] data, int pos) {

        String text = new String (data);
        
        switch (m_cellIndex) {
            case 0:
            	m_validUrl = true;
            	//System.out.println("Cell Index = "+ m_cellIndex + "; Text = "+text);
                break;

            case 1:
            	m_validUrl = false;
                //System.out.println("Cell Index = "+m_cellIndex+"; Text = "+text);
                break;

            case 2:
                //System.out.println("Cell Index = "+m_cellIndex+"; Text = "+text);
                break;

            case 3:
                //System.out.println("Cell Index = "+m_cellIndex+"; Text = "+text);

                Date lastMofiedDate = null;
                if ( ( text != null ) && ( text.trim().length() != 0 ) )
                {
                    text = text.trim();
                    if(text.indexOf("/") != -1)
                    {
                        String strlastModifiedDate = text.substring(0,10);
                        //System.out.println( "Last Modified Date" + strlastModifiedDate);
                        lastMofiedDate = StringUtils.format( strlastModifiedDate, "yyyy/MM/dd" );
                        if( lastMofiedDate != null )
                        {
                           if ( DateUtil.getElapsedDays( lastMofiedDate ) <= sortLotBinDaysDiff )
                           {
                                m_urlList.add(m_urlString);
                		        //System.out.println("Download link = "+m_urlString);
                           }

                        }
                    }
                }
                break;

            default:
                break;
        }

    }

    //Replaces the hexadecimal code
    private String parseLotBinSummaryDownloadLink(String urlString){

	  urlString = urlString.replaceAll("%5F", "_");
	  urlString = urlString.replaceAll("%2D", "-");
	  urlString = urlString.replaceAll("%2E", ".");

	  return ("/cisweb/quality/static_rpt/"+urlString);
    }

    // Resets the objects state
    public void reset() {

        m_cellOpen = false;
        m_cellIndex = -1;

    }
}
